package com.mtx.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mtx.dao.MUser;
import com.mtx.service.MUserService;

import com.mtx.util.Message;
import com.mtx.util.RedisUtil;
import com.mtx.vo.LoginReq;
import com.mtx.vo.RegisterReq;
import ma.glasnost.orika.impl.DefaultMapperFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.WebApplicationContext;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.params.SetParams;

import java.util.UUID;

@RestController
public class LogController  {

    @Autowired
    private MUserService userService;

    @PostMapping("login")
    @ResponseBody
    public Message login(@RequestBody LoginReq loginReq){
        MUser email = userService.getOne(new QueryWrapper<MUser>().ge("email", loginReq.getEmail()));
        long expireSecond;
        if (loginReq.getRem()){
            expireSecond = 360000L;
        }else {
            expireSecond = 36000L;
        }
        if (email!=null&&email.getPwd().equals(loginReq.getPassword())){
            String uuid = UUID.randomUUID().toString();
            try (Jedis jedis = RedisUtil.pool.getResource()) {
                jedis.auth("990812");
                jedis.set(uuid, email.getId(),new SetParams().ex(expireSecond));
            }
            return Message.success(uuid);
        }
        return Message.fail();
    }

    @PostMapping("register")
    @ResponseBody
    public String register(@RequestBody RegisterReq registerReq){
        try {
            DefaultMapperFactory build = new DefaultMapperFactory.Builder().build();
            build.classMap(RegisterReq.class,MUser.class).field("password","pwd").byDefault().register();
            MUser mUser = build.getMapperFacade().map(registerReq, MUser.class);
            this.userService.save(mUser);
        }catch (Exception e ){
            e.printStackTrace();
        }
        return "";

    }
}
